package cn.springBoot;

import java.net.URL;
import java.util.Date;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.HttpMethod;
import com.amazonaws.Protocol;
import com.amazonaws.SDKGlobalConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.S3ClientOptions;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;

/**
 * <p>
 * 京东云 oss 获取预签名url
 * </p>
 *
 * @author ljx
 * @class cn.springBoot.PresignUrl
 * @create date: 2021/12/31
 */
public class PresignUrl {

    static AmazonS3 createS3Client(String accessKey, String secretKey, String endpoint) {
        System.setProperty(SDKGlobalConfiguration.ENABLE_S3_SIGV4_SYSTEM_PROPERTY, "true");
        AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
        ClientConfiguration config = new ClientConfiguration();
        config.setProtocol(Protocol.HTTP);
        AmazonS3 s3 = new AmazonS3Client(awsCredentials, config);
        s3.setEndpoint(endpoint);
        S3ClientOptions options = new S3ClientOptions();
        options.withChunkedEncodingDisabled(true); // Must have
        s3.setS3ClientOptions(options);
        return s3;
    }

    static public URL generatePresignUrl(String accessKey, String secretKey, String endpoint, String bucketName,
        String keyName, HttpMethod method, Date expiration) {
        AmazonS3 s3 = createS3Client(accessKey, secretKey, endpoint);
        GeneratePresignedUrlRequest request =
            new GeneratePresignedUrlRequest(bucketName, keyName).withMethod(method).withExpiration(expiration);
        return s3.generatePresignedUrl(request);
    }

    static public void main(String[] str) {
        final String accessKey = "JDC_FF039D538E8A78DC126504A3511A";
        final String secretKey = "1153BFCCB5B7AC2A8169948CDF009441";
        final String endpoint = "s3.cn-north-1.jdcloud-oss.com";
        final String bucketName = "test-jdy/file";
        final String keyName = "1";
        final HttpMethod method = HttpMethod.PUT; // 此处设置您的PresignUrl允许的HTTP方法
        final Integer expireInSeconds = 100; // 此处设置您的PresignUrl有效的时间段，以秒为单位
        final Date expiration = new Date(System.currentTimeMillis() + expireInSeconds * 1000);

        URL url = generatePresignUrl(accessKey, secretKey, endpoint, bucketName, keyName, method, expiration);
        System.out.println("Pre-Signed URL: " + url);
    }
}
